<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button
          v-if="meta.indexOf('TicketOrderExcel') > -1"
          :loading="exportLoading"
          type="primary"
          @click="handleExport"
          >{{ $t("message.daochu") }}</el-button
        >
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.ddh')"
        min-width="220"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.orderId)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.ddxq')"
        min-width="200"
        show-overflow-tooltip
        prop="orderInfo"
      />
      <el-table-column
        align="center"
        :label="$t('message.ddhj')"
        prop="allPrice"
        min-width="100"
      />
      <el-table-column
        align="center"
        :label="$t('message.ddly')"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.channelTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.zffs')"
        min-width="140"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.payMethodName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.memberInfo')"
        prop="memberName"
        min-width="240"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('message.bz')"
        min-width="200"
        align="center"
        prop="remarks"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.czy')"
        prop="creator"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.createTime')"
        prop="createTime"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.ddzt')"
        min-width="100"
        show-overflow-tooltip
        fixed="right"
      >
        <template slot-scope="scope">
          <span
            v-if="scope.row.status == '0'"
            class="primaryColor pointer"
            @click="getOrderType(scope.row.orderId)"
            >{{ scope.row.statusName }}</span
          >
          <span v-else>{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH' ? 180 : 320"
        fixed="right"
      >
        <template slot-scope="scope">
          <div
            v-if="scope.row.status == '0' || scope.row.status == '3'"
            class="flex-cc"
          >
            <el-button
              v-if="
                (scope.row.status == '0' &&
                  meta.indexOf('TicketOrderPayContinue') > -1) ||
                (scope.row.status == '3' &&
                  meta.indexOf('TicketOrderCancel') > -1)
              "
              v-preventReClick
              type="text"
              @click="firstAction(scope.row.orderId, scope.row.status)"
              >{{
                scope.row.status == "0" ? $t("message.jxzf") : $t("message.tk")
              }}</el-button
            >
            <el-button
              v-if="
                (scope.row.status == '0' &&
                  meta.indexOf('TicketOrderPayCancel') > -1) ||
                (scope.row.status == '3' &&
                  meta.indexOf('TicketPrinterOrder') > -1)
              "
              v-preventReClick
              type="text"
              @click="secondAction(scope.row.orderId, scope.row.status)"
              >{{
                scope.row.status == "0"
                  ? $t("message.qxgm")
                  : $t("message.dyxp")
              }}</el-button
            >
          </div>
          <div v-else class="flex-cc">-</div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @SizeChange="pageSizeChange"
      @current-change="getList"
    />
    <orderDialog ref="child" @orderSuccess="getList" />
    <orderDetail ref="orderDetail" />
    <printTem v-if="isPrint" ref="printTemRef" />
    <PrintTable
      ref="PrintTableRef"
      @cancelDialog="cancelDialog"
      @printd="printd"
    />
    <closeReserve ref="closeReserve" @closeSccess="getList()" />
  </div>
</template>

<script>
import {
  getProjectList,
  ticketOrders,
  ticketBuyCancel,
  ticketOrderCancel,
  orderType,
  allConfigList,
  printOrder,
  qxDdList,
  ticketOrderExport,
  getOrderTypeQuery,
  getChannelType,
} from "@/api";
import { parseTime } from "@/utils";
import orderDialog from "@/components/order";
import Paginations from "@/components/paginations/paginations";
import QueryForm from "@/components/QueryForm";
import orderDetail from "./orderDetail";
import { TJshortcuts } from "@/utils/config";
import printTem from "@/components/printTem";
import PrintTable from "@/components/printTable.vue";
import closeReserve from "../closeReserve.vue";
export default {
  name: "TicketOrder",
  components: {
    orderDialog,
    QueryForm,
    orderDetail,
    PrintTable,
    Paginations,
    printTem,
    closeReserve,
  },
  data() {
    return {
      isShowPrint: false,
      exportLoading: false,
      printList: [],
      isPrint: false,
      queryFormConfig: {
        formItems: [
          {
            filed: "orderId",
            type: "input",
            label: this.$t("message.ddbh"),
            clearable: true,
          },
          {
            filed: "projectId",
            type: "select",
            label: this.$t("message.syxm"),
            placeholder: this.$t("message.qxz") + this.$t("message.xm"),
            clearable: true,
            options: [],
          },
          {
            filed: "ticketName",
            type: "input",
            label: this.$t("message.mpmc"),
            clearable: true,
          },
          {
            filed: "channelType",
            type: "select",
            label: this.$t("message.ddly"),
            clearable: true,
            options: [],
          },
          {
            filed: "payMethod",
            type: "select",
            label: this.$t("message.zffs"),
            clearable: true,
            options: [],
          },
          {
            filed: "payStatus",
            type: "select",
            label: this.$t("message.ddzt"),
            clearable: true,
            labelCode: "name",
            options: [],
          },
          {
            filed: "memberNameOrPhone",
            type: "input",
            label: this.$t("message.memberInfo"),
            placeholder: this.$t("message.hy2"),
            clearable: true,
          },
          {
            filed: "time",
            label: this.$t("message.xdrq"),
            type: "daterange",
            clearable: true,
            pickerOptions: {
              shortcuts: TJshortcuts,
            },
          },
        ],
        online: true,
      },
      meta: [],
      payMessage: {},
      list: [],
      total: 0,
      pagination: {
        page: 1,
        rows: 10,
      },
      listLoading: true,
      openStatus: [
        { value: "1", label: this.$t("message.zcyy") },
        { value: "0", label: this.$t("message.tiye") },
      ],
      payTypes: [],
      orderStatuss: [
        { value: "0", label: this.$t("message.dzf") },
        { value: "1", label: this.$t("message.cswzf") },
        { value: "2", label: this.$t("message.qxzf") },
        { value: "3", label: this.$t("message.zfcg") },
        { value: "4", label: this.$t("message.tkz") },
        { value: "5", label: this.$t("message.tkcg") },
      ],
      filters: {},
    };
  },
  created() {
    console.log(this.$route.meta, "订单列表页面");
    this.meta = this.$route.meta.buttons || [];
    this.getInitData();
    allConfigList({ param: { type: "2", code: "1" } })
      .then((res) => {
        if (res.errorCode !== "000000") return;
        this.payTypes = res.recordList;
        const arr = res.recordList;
        arr.forEach((e) => {
          e.label = e.name;
        });
        this.queryFormConfig.formItems[4].options = arr;
      })
      .catch((err) => {
        console.log(err);
      });
    this.getOrderStatusList();
    this.getChannel();
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  methods: {
    cancelBtn(e) {
      this.getDdList(e);
    },
    getDdList(e) {
      qxDdList({ param: { orderId: e } }).then((res) => {
        if (res.errorCode === "000000") {
          let list = res.recordList;
          this.$refs.closeReserve.cancelBtn(list, []);
        }
      });
    },
    printTC(id) {
      if (window.Android) {
        Android.print("TICKETTPML", id, "");
        return;
      }
      this.isPrint = true;
      printOrder({
        param: {
          contentMap: {},
          venueId: sessionStorage.getItem("venueId"),
          workId: id,
          templateCode: "TICKETTPML",
        },
      })
        .then((res) => {
          if (
            res.record &&
            res.record.isPrint === "1" &&
            res.record.dataList &&
            res.record.dataList.length > 0
          ) {
            this.printList = res.record.dataList;
            if (res.record.dataList.length === 1) {
              res.record.dataList.forEach((item) => {
                this.$refs.printTemRef.obj = { ...item };
                setTimeout(() => {
                  this.$refs.printTemRef.print();
                }, 300);
                setTimeout(() => {
                  this.isPrint = false;
                }, 500);
              });
            } else {
              this.isPrint = false;
              this.$refs.PrintTableRef.showDetail(res.record);
            }
          } else {
            this.isPrint = false;
          }
        })
        .catch(() => {
          this.isPrint = false;
        });
    },
    printd(index) {
      this.isPrint = true;
      const arr = [...this.printList];
      setTimeout(() => {
        this.$refs.printTemRef.obj = { ...arr[index] };
      }, 300);
      setTimeout(() => {
        this.$refs.printTemRef.print();
      }, 500);
      setTimeout(() => {
        this.isPrint = false;
      }, 1000);
    },
    cancelDialog() {
      this.isPrint = false;
    },
    getChannel() {
      getChannelType({ param: { code: "CHANNEL_TICKET" } }).then((res) => {
        this.queryFormConfig.formItems[3].options = res.recordList.map(
          (item) => {
            return {
              label: item.name,
              value: item.value,
            };
          }
        );
      });
    },
    getOrderStatusList() {
      getOrderTypeQuery({ param: {} }).then((res) => {
        this.queryFormConfig.formItems[5].options = res.recordList || [];
      });
    },
    pageSizeChange(val) {
      this.pagination.rows = val;
      this.getList(1);
    },
    handleExport() {
      const { filters } = this;
      if (filters.time) {
        filters.startDate = filters.time[0];
        filters.endDate = filters.time[1];
      } else {
        filters.startDate = "";
        filters.endDate = "";
      }
      this.exportLoading = true;
      ticketOrderExport({
        param: {
          ...filters,
          venueId: sessionStorage.getItem("venueId"),
        },
      })
        .then((res) => {
          this.exportLoading = false;
          if (res.errorCode === "000000") {
            if (window.Android) {
              Android.downloadFile(res.record.showUrl);
              return;
            }
            const a = document.createElement("a"); // 创建一个a标签元素
            a.style.display = "none"; // 设置元素不可见
            a.href = res.record.showUrl; // 设置下载地址
            document.body.appendChild(a); // 加入
            a.click(); // 触发点击,下载
            document.body.removeChild(a); //
            this.$message.success(this.$t("message.dccg"));
          }
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    handleDetail(id) {
      // this.$router.push({ name: 'ticketOrderDetail', query: { id }})
      this.$refs.orderDetail.getTicketOrderDetail(id);
    },
    getOrderType(orderId) {
      orderType({
        param: {
          orderId,
        },
      })
        .then((res) => {
          const str = res.record.msg;
          if (res.errorCode === "000000") {
            if (res.record.code === "0") {
              this.$message.success(str);
              this.getList(1);
            } else if (res.record.code === "2") {
              this.$message.info(str);
            } else {
              this.$message.error(str);
              this.getList(1);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    nameWithPayMethod(payM) {
      const temp = this.payTypes.find((item) => item.value === payM);
      return temp ? temp.name : "";
      // for (const item of this.payTypes) {
      //   if (item.value === payM) {
      //     return item.name
      //   }
      // }
      // return '-'
    },
    orderStatus(status) {
      const temp = this.orderStatuss.find((item) => item.value === status);
      return temp ? temp.label : "";
    },
    getInitData() {
      getProjectList({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          projectName: "",
          type: "1",
          status: "",
        },
      }).then((res) => {
        if (res.errorCode !== "000000") return;
        const arr = res.recordList;
        arr.forEach((e) => {
          e.label = e.projectName;
          e.value = e.id;
        });
        // this.projectList = arr
        this.queryFormConfig.formItems[1].options = arr;
        // this.projectList = res.recordList
      });
      this.getList();
    },
    getList(page) {
      const { filters, pagination } = this;
      if (page) {
        pagination.page = page;
        this.pagination.page = Number(page);
      }
      pagination.firstQueryTime = parseTime(new Date());
      if (filters.time) {
        filters.startDate = filters.time[0];
        filters.endDate = filters.time[1];
      } else {
        filters.startDate = "";
        filters.endDate = "";
      }
      this.listLoading = true;
      ticketOrders({
        pagination,
        param: {
          ...filters,
          venueId: sessionStorage.getItem("venueId"),
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode === "000000") {
            this.list = res.recordList;
            this.total = res.totalCount;
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    clear() {
      this.filters = {};
      this.getList(1);
    },
    firstAction(id, status) {
      if (status === "0") {
        // 继续支付
        this.$refs.child.continuePay(id, "ticketOrder");
      } else {
        // 取消订单
        this.cancelBtn(id);
        // this.$alert(this.$t('message.qxddtc'), this.$t('message.jingao'), {
        //   confirmButtonText: this.$t('message.qd'),
        //   callback: (action) => {
        //     if (action === 'confirm') {
        //       ticketOrderCancel({ param: { id } })
        //         .then((res) => {
        //           if (res.errorCode !== '000000') return
        //           this.getList(1)
        //         })
        //     }
        //   }
        // })
      }
    },
    secondAction(id, status) {
      if (status === "0") {
        // 取消购买
        this.$alert(this.$t("message.qxgmtc"), this.$t("message.jingao"), {
          confirmButtonText: this.$t("message.qd"),
          callback: (action) => {
            if (action === "confirm") {
              ticketBuyCancel({ param: { id } }).then((res) => {
                if (res.errorCode !== "000000") return;
                this.getList(1);
              });
            }
          },
        });
      } else {
        this.printTC(id);
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 20px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}
</style>
